#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy
import cv2
import json
from flask import Flask
from flask import Blueprint
from flask import request, Response
import os
import rospy
import json
import numpy
from sensor_msgs.msg import PointCloud2
from sensor_msgs.msg import PointField
import numpy as np
from tool.common import *

opencv_server = Blueprint("/opencv", __name__)

#---------------------------------#
#******#   flask-网络端口验证   #******#
#---------------------------------#
@opencv_server.before_request
def before():
    res_data = before_user(request)
    if res_data:
        return Response(json.dumps(res_data),  mimetype='application/json')


@opencv_server.route('/opencv_rect', methods=['POST'])
def opencv_rect():
#     # 计算点集的最小矩形 https://cxybb.com/article/yukinoai/87892718
#     # 请求数据格式 数据类型 要为int类型
#     data = request.json["data"]
#     # data = [[1, 2], [3, 3], [5, 6], [7, 9], [6, 9]]
#     cnt = numpy.array(data)
#     rect = cv2.minAreaRect(cnt)  # 得到最小外接矩形的（中心(x,y), (宽,高), 旋转角度）
#     box = cv2.boxPoints(rect)
#     # numpy float 转换 https://blog.csdn.net/qq_41982466/article/details/123272615
#     data = {"lt": [box[0][0].tolist(), box[0][1].tolist()],
#             "rt": [box[1][0].tolist(), box[1][1].tolist()],
#             "lb": [box[2][0].tolist(), box[2][1].tolist()],
#             "rb": [box[3][0].tolist(), box[3][1].tolist()]
#             }
#     ret_dat = {}
#     ret_dat["data"] = data
#     ret_dat["ret"]='success';ret_dat["code"]=0
    
#     return Response(json.dumps(ret_dat),  mimetype='application/json')
   ret_dat = {};ret_dat["msg"]='success';ret_dat["code"]=0
   try:
      data = request.json["data"]
      cnt = numpy.array(data)
      rect = cv2.minAreaRect(cnt)
      box = cv2.boxPoints(rect)
      data = {"lt": [box[0][0].tolist(), box[0][1].tolist()],
            "rt": [box[1][0].tolist(), box[1][1].tolist()],
            "lb": [box[2][0].tolist(), box[2][1].tolist()],
            "rb": [box[3][0].tolist(), box[3][1].tolist()]
            }
      ret_dat["data"] = data
   except Exception as error:
      ret_dat["code"]=-1
      #ret_dat["ret"]='fail'
      ret_dat["msg"]=str(error)
      err_msg = "[MapParser]opencv_rect: {}".format(str(error))
      log.LogError(self.GetNodeName(),err_msg)
      rospy.logerr(err_msg)
   finally:
      return Response(json.dumps(ret_dat),  mimetype='application/json')

   #下面这一段有语法错误（正在找。。。）
   # try:
   #    data = request.json["data"]
   #    # data = [[1, 2], [3, 3], [5, 6], [7, 9], [6, 9]]
   #    cnt = numpy.array(data)
   #    rect = cv2.minAreaRect(cnt)  # 得到最小外接矩形的（中心(x,y), (宽,高), 旋转角度）
   #    box = cv2.boxPoints(rect)
   #    # numpy float 转换 https://blog.csdn.net/qq_41982466/article/details/123272615
   #    data = {"lt": [box[0][0].tolist(), box[0][1].tolist()],
   #             "rt": [box[1][0].tolist(), box[1][1].tolist()],
   #             "lb": [box[2][0].tolist(), box[2][1].tolist()],
   #             "rb": [box[3][0].tolist(), box[3][1].tolist()]
   #    }

   #    ret_dat["data"] = data

   # except Exception as error:
   #    ret_dat["code"]=-1 
   #    ret_dat["ret"]='fail'
   #    ret_dat["msg"]=str(error)

   #    err_msg = "[MapParser]opencv_rect: {}".format(str(error))
   #    log.LogError(self.GetNodeName(),err_msg)  
   #    rospy.logerr(err_msg)
   # finally:
   #    return Response(json.dumps(ret_dat),  mimetype='application/json')

